1. MongoDB Update Operations
Definition
MongoDB update operations modify existing documents in a collection. The update operations provide various methods to update document fields, including setting new values, incrementing values, updating arrays, and performing complex updates using operators.
Algorithm 1: Basic Document Update :-
Example 1: Basic Field Update
// Update student grade
db.students.updateOne(
{ name: "John Doe" },
{
$set: {
grade: "A",
lastUpdated: new Date()
}
}
)
Algorithm 2: Array Update Operations :-
Example 2: Array Update
// Update array elements
db.users.updateOne(
{ _id: ObjectId("123") },
{
$push: {
hobbies: "reading"
},
$pull: {
oldHobbies: "gaming"
}
}
)
Algorithm 3: Multiple Document Update :-
Example 3: Multiple Document Update
// Update multiple documents
db.products.updateMany(
{ category: "electronics" },
{
$inc: { price: 10 },
$set: {
updated: true,
lastModified: new Date()
}
}
)